<template>
  <div class="transfer-manager">
    <!-- 传输面板 -->
    <el-drawer v-model="showPanel" title="传输任务管理" direction="rtl" size="350px">
      <div class="drawer-content">
        <div class="panel-header">
          <span>{{ activeTasks.length }} 个正在进行，共 {{ tasks.length }} 个任务</span>
          <div>
            <el-button type="danger" size="small" @click="clearCompletedTasks" :disabled="!completedTasks.length">
              清除已完成
            </el-button>
          </div>
        </div>

        <div class="task-list" v-if="tasks.length">
          <div v-for="task in tasks" :key="task.id" class="task-item">
            <div class="task-header">
              <div class="task-icon">
                <el-icon v-if="task.type === 'upload'">
                  <Upload />
                </el-icon>
                <el-icon v-else>
                  <Download />
                </el-icon>
              </div>
              <div class="task-title">
                <div class="file-name" :title="task.fileName">{{ task.fileName }}</div>
                <div class="task-status">
                  <template v-if="task.status === 'running'">
                    {{ formatSize(task.processedSize) }} / {{ formatSize(task.totalSize) }}
                    {{ task.speed ? `- ${task.speed}/s` : '' }}
                  </template>
                  <template v-else-if="task.status === 'completed'">
                    <span class="success-text">传输完成</span>
                  </template>
                  <template v-else-if="task.status === 'failed'">
                    <span class="error-text">{{ task.error || '传输失败' }}</span>
                  </template>
                  <template v-else-if="task.status === 'canceled'">
                    <span class="muted-text">已取消</span>
                  </template>
                  <template v-else>
                    <span>准备中...</span>
                  </template>
                </div>
              </div>
              <div class="task-actions">
                <el-button v-if="task.status === 'running'" @click="cancelTask(task.id)" type="danger" size="small"
                  circle :icon="Close">
                </el-button>
                <el-button v-else-if="['completed', 'failed', 'canceled'].includes(task.status)"
                  @click="removeTask(task.id)" type="info" size="small" circle :icon="Delete">
                </el-button>
              </div>
            </div>
            <div class="task-progress">
              <el-progress :percentage="task.progress" :status="getProgressStatus(task)"
                :indeterminate="task.status === 'running' && !task.progress" :striped="task.status === 'running'"
                :stroke-width="6">
              </el-progress>
            </div>
          </div>
        </div>

        <div class="empty-state" v-else>
          <el-empty description="暂无传输任务" />
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { Upload, Download, Close, Delete } from '@element-plus/icons-vue';

// 传输任务列表
const tasks = ref([]);
const showPanel = ref(false);

// 计算活动任务
const activeTasks = computed(() => {
  return tasks.value.filter(task => task.status === 'running');
});

// 计算已完成任务
const completedTasks = computed(() => {
  return tasks.value.filter(task => ['completed', 'failed', 'canceled'].includes(task.status));
});

// 显示/隐藏面板
const togglePanel = () => {
  console.log('切换传输面板显示状态，当前状态:', showPanel.value);
  showPanel.value = !showPanel.value;
};

// 强制显示面板
const showTransferPanel = () => {
  console.log('强制显示传输面板');
  showPanel.value = true;
};

// 强制隐藏面板
const hideTransferPanel = () => {
  console.log('强制隐藏传输面板');
  showPanel.value = false;
};

// 格式化文件大小
const formatSize = (bytes) => {
  if (bytes === 0 || !bytes) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
};

// 获取进度条状态
const getProgressStatus = (task) => {
  if (task.status === 'running') return '';
  if (task.status === 'completed') return 'success';
  if (task.status === 'failed') return 'exception';
  return 'info';
};

// 速度计算相关变量
const speedTracking = ref({});

// 添加新的传输任务
const addTask = (task) => {
  console.log('添加新传输任务', task);
  const id = Date.now().toString();
  const newTask = {
    id,
    fileName: task.fileName || '未命名文件',
    type: task.type || 'download',
    status: 'waiting',
    progress: 0,
    processedSize: 0,
    totalSize: task.totalSize || 0,
    speed: '',
    error: null,
    onCancel: task.onCancel || null,
    startTime: Date.now()
  };

  // 初始化速度跟踪
  speedTracking.value[id] = {
    lastUpdate: Date.now(),
    lastProcessed: 0,
    lastSpeeds: []
  };

  tasks.value.unshift(newTask);
  return id;
};

// 更新任务状态
const updateTask = (id, updates) => {
  const taskIndex = tasks.value.findIndex(t => t.id === id);
  if (taskIndex === -1) return;

  const task = tasks.value[taskIndex];
  const updatedTask = { ...task, ...updates };

  // 计算传输速度
  if (updates.processedSize !== undefined && task.status === 'running') {
    const now = Date.now();
    const tracking = speedTracking.value[id];

    if (tracking) {
      const timeElapsed = (now - tracking.lastUpdate) / 1000; // 秒
      if (timeElapsed >= 0.5) { // 至少0.5秒更新一次速度
        const processed = updates.processedSize;
        const processed_delta = processed - tracking.lastProcessed;
        const speed_bps = processed_delta / timeElapsed;

        // 保存最近5次速度值取平均，让速度显示更平滑
        tracking.lastSpeeds.push(speed_bps);
        if (tracking.lastSpeeds.length > 5) {
          tracking.lastSpeeds.shift();
        }

        const avgSpeed = tracking.lastSpeeds.reduce((sum, s) => sum + s, 0) / tracking.lastSpeeds.length;
        updatedTask.speed = formatSize(avgSpeed);

        // 更新跟踪数据
        tracking.lastUpdate = now;
        tracking.lastProcessed = processed;
      }
    }
  }

  tasks.value[taskIndex] = updatedTask;
};

// 完成任务
const completeTask = (id, success = true, errorMessage = null) => {
  const taskIndex = tasks.value.findIndex(t => t.id === id);
  if (taskIndex === -1) return;

  const task = tasks.value[taskIndex];
  const updates = {
    status: success ? 'completed' : 'failed',
    progress: success ? 100 : task.progress,
    error: errorMessage
  };

  // 如果是成功完成，确保进度和处理大小正确
  if (success && task.totalSize) {
    updates.processedSize = task.totalSize;
  }

  // 更新任务
  tasks.value[taskIndex] = { ...task, ...updates };

  // 清理速度跟踪
  delete speedTracking.value[id];
};

// 取消任务
const cancelTask = (id) => {
  const task = tasks.value.find(t => t.id === id);
  if (!task) return;

  // 执行取消回调
  if (task.onCancel && typeof task.onCancel === 'function') {
    task.onCancel();
  }

  // 更新任务状态
  updateTask(id, {
    status: 'canceled',
    progress: task.progress,
  });

  // 清理速度跟踪
  delete speedTracking.value[id];
};

// 删除单个任务
const removeTask = (id) => {
  const index = tasks.value.findIndex(t => t.id === id);
  if (index !== -1) {
    tasks.value.splice(index, 1);
  }
};

// 清除已完成任务
const clearCompletedTasks = () => {
  tasks.value = tasks.value.filter(task => task.status === 'running' || task.status === 'waiting');
};

// 监听自定义事件
onMounted(() => {
  console.log('传输管理器已挂载');

  // 添加全局事件监听
  window.addEventListener('show-transfer-panel', () => {
    console.log('接收到显示传输面板事件');
    showPanel.value = true;
  });

  window.addEventListener('add-transfer-task', (event) => {
    console.log('接收到添加传输任务事件', event.detail);
    if (event.detail && event.detail.task) {
      const taskId = addTask(event.detail.task);
      console.log('任务已添加，ID:', taskId);
      // 如果任务状态是running，自动更新
      if (event.detail.task.status === 'running') {
        updateTask(taskId, { status: 'running' });
      }
    }
  });

  // 导出实例到window对象，方便全局访问
  window.transferManager = {
    addTask: (task) => {
      console.log('添加任务:', task);
      const taskId = addTask(task);
      // 如果添加任务后面板关闭，自动显示面板
      if (!showPanel.value && task.autoShowPanel !== false) {
        showPanel.value = true;
      }
      return taskId;
    },
    updateTask: (id, updates) => {
      console.log('更新任务:', id, updates);
      updateTask(id, updates);
    },
    completeTask: (id, success, errorMessage) => {
      console.log('完成任务:', id, success, errorMessage);
      completeTask(id, success, errorMessage);
    },
    cancelTask: (id) => {
      console.log('取消任务:', id);
      cancelTask(id);
    },
    showPanel: () => {
      console.log('显示面板');
      showPanel.value = true;
    },
    hidePanel: () => {
      console.log('隐藏面板');
      showPanel.value = false;
    },
    togglePanel: () => {
      console.log('切换面板');
      showPanel.value = !showPanel.value;
    }
  };

  console.log('传输管理器已全局注册到window.transferManager');
});

// 组件提供的方法
defineExpose({
  addTask,
  updateTask,
  completeTask,
  cancelTask,
  togglePanel,
  showTransferPanel,
  hideTransferPanel
});
</script>

<style scoped>
.drawer-content {
  padding: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px 10px;
  border-bottom: 1px solid #dcdfe6;
  margin-bottom: 10px;
}

.task-list {
  flex: 1;
  overflow-y: auto;
}

.task-item {
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  background-color: #f5f7fa;
  transition: background-color 0.3s;
}

.task-item:hover {
  background-color: #e6ebf5;
}

.task-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.task-icon {
  font-size: 18px;
  margin-right: 10px;
  width: 24px;
  text-align: center;
  color: #409EFF;
}

.task-title {
  flex: 1;
  overflow: hidden;
}

.file-name {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 220px;
  margin-bottom: 4px;
}

.task-status {
  font-size: 12px;
  color: #606266;
}

.task-progress {
  margin-top: 5px;
}

.success-text {
  color: #67c23a;
}

.error-text {
  color: #f56c6c;
}

.muted-text {
  color: #909399;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}
</style>